package ParsingSAX;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

@SuppressWarnings("serial")
public class NodeTransferHandler extends TransferHandler {

	public NodeTransferHandler(){
		super();
		System.out.println("init nodetrasnferhandler");
	}
	
	public int getSourceActions(JComponent c) {
		System.out.println("method getSourceActions");
		if (c.getTransferHandler() != null)
			return COPY;

		else
			return NONE;
	}

	public NodeTransferable createTransferable(JComponent c) {
		System.out.println("method createTransferable");
		JTree tree = (JTree) c;
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
				.getLastSelectedPathComponent();
		// TreePath[] paths=tree.getSelectionPaths() ;

		NodeTransferable t = new NodeTransferable(node);

		return t;

	}

	public boolean canImport(TransferHandler.TransferSupport support) {
		System.out.println("method canImport");
		if (support.isDrop()
				&& support.getTransferable().isDataFlavorSupported(
						NodeTransferable.nodeFlavor))

			return true;

		else
			return false;

	}

	public boolean importData(TransferSupport support) {
		System.out.println("method importData");
		if (canImport(support)) {
			try {
				Transferable t = support.getTransferable();
				
				DefaultMutableTreeNode dmt = (DefaultMutableTreeNode) t
						.getTransferData(NodeTransferable.nodeFlavor);
				JTree.DropLocation dl = (JTree.DropLocation) support
						.getDropLocation();
				TreePath tp = dl.getPath();
				if (tp == null) {
					return false;
				}
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) tp
						.getLastPathComponent();
				if (parent.getUserObject() instanceof Contact) {
					return false;
				}
				JTree tree = (JTree) support.getComponent();
				DefaultTreeModel tm = (DefaultTreeModel) tree.getModel();
				parent.add(dmt);
				tm.reload();
				tree.expandPath(tp);
				return true;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}

}
